const express = require("express");
const router = express.Router();
const ResponseHelper = require("./ResponseHelper");
const file = require("./../tools/file");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const moment = require("moment");
const axios = require("axios");

// 使用 diskStorage 直接保存到目标目录
const storage = multer.diskStorage({
  destination: (req, fileData, cb) => {
    try {
      const { sNo, pos } = req.query;
      const date = moment().format("YYYY-MM-DD");
      const targetDir = path.join(file.imgSavePath, date, sNo, pos);
      fs.mkdirSync(targetDir, { recursive: true });
      cb(null, targetDir);
    } catch (err) {
      cb(err);
    }
  },
  filename: (req, fileData, cb) => {
    const ext = path.extname(fileData.originalname) || ".jpg";
    const { sNo } = req.query;
    const date = moment().format("YYYY-MM-DD-HH-mm-ss");
    const fileName = `${sNo}-${date}` + ext;
    cb(null, fileName);
  },
});

const upload = multer({ storage });

router.post("/uploadBinary", upload.single("Data"), (req, res) => {
  try {
    ResponseHelper.sendData("上传成功", res);
  } catch (err) {
    console.error(err);
    ResponseHelper.sendErr("上传失败", res);
  }
});

// 保存远程图片函数
async function downloadImage(imgUrl, savePath) {
  const response = await axios({
    url: imgUrl,
    method: "GET",
    responseType: "stream", // 以流的方式获取
  });
  return new Promise((resolve, reject) => {
    const writer = fs.createWriteStream(savePath);
    response.data.pipe(writer);
    writer.on("finish", resolve);
    writer.on("error", reject);
  });
}

router.post("/uploadSelectedImgs", async (req, res) => {
  try {
    const { sNo, pos, imgs } = req.body;
    if (!sNo || !pos || !Array.isArray(imgs)) {
      return ResponseHelper.sendErr("参数缺失", res);
    }
    const date = moment().format("YYYY-MM-DD");
    const targetDir = path.join(file.imgSavePath, date, sNo, pos);
    fs.mkdirSync(targetDir, { recursive: true });
    // 遍历下载
    const savedFiles = [];
    for (const imgUrl of imgs) {
      const ext = path.extname(imgUrl) || ".jpg";
      const timestamp = moment().format("YYYY-MM-DD-HH-mm-ss-SSS");
      const fileName = `${sNo}-${timestamp}${ext}`;
      const savePath = path.join(targetDir, fileName);
      await downloadImage(imgUrl, savePath);
      savedFiles.push(savePath);
    }
    ResponseHelper.sendData({ message: "上传成功", files: savedFiles }, res);
  } catch (err) {
    console.error(err);
    ResponseHelper.sendErr("上传失败", res);
  }
});
module.exports = router;
